import $ from './jquery.esm.js';
import cookie from './cookie.js';
// console.log(111);
let id = location.search.split('=')[1];
// 
$.ajax({
  type: "get",
  url: "../../interface/getitems.php",
  data: { id },
  dataType: "json"
}).then(res => {
  // console.log(res);
  let arr=res.filter(e=>e.id==id)
  // console.log(arr);
$('.d3-2-1').html(arr[0].title)
$('#iii').html(arr[0].price)
  let arr1=JSON.parse(arr[0].picture)
  $('#lan2>img').attr('src',`${arr1[0].src}`)
    // console.log(arr1[0].src);
  $('#lan1>img').attr('src',`${arr1[0].src}`)
    // console.log(arr1[1].src);
    // console.log( $('#foot>img'));
  $('#foot>img').attr('src',`${arr1[1].src}`)
  // $('.foot').html(arr[1].src)

  // let pic = JSON.parse(res.picture);


  // $('#lan1').html(template);

  $('#additem').on('click', function () {
    addItem(arr[0].id, $('#num').val());
  });



}).catch(xhr => {
  console.log(xhr.status);
});

function addItem(id,num){

  let product = {id,num};
  // console.log(product);
  let shop = cookie.get('shop'); // 从cookie中获得数据
// console.log(shop);
  if (shop) {
    // let index = shop.findIndex(elm => elm.id == id); // 获得商品对象在数组中的索引
    // let count = parseInt(shop[index].num);
    // count += parseInt(num);
    // shop[index].num = count;
    shop = JSON.parse(shop);

    // 当商品id在cookie数据中已经存在时 需要修改数量 而不是添加商品
    if (shop.some(el => el.id == id)) {
      let index = shop.findIndex(elm => elm.id == id); // 获得商品对象在数组中的索引
      let count = parseInt(shop[index].num);
      count += parseInt(num);
      shop[index].num = count;
    } else {
      shop.push(product);
    }
  } else {
    shop = [];
    shop.push(product);
  }

  cookie.set('shop', JSON.stringify(shop));  // 将数组转换成JSON字符串存入cookie
}